


import { onMounted, ref, watchEffect } from "vue"
const STORE_KEY = 'STORE_KEY_XUANXIAOQIAN'

/**
 * 用于将Ref持久化
 * const value = useLocalStorage('xxxxx', null, 100)
 * @param storeKey storeName
 * @param defaultValue 变量默认值
 * @param ttlSeconds 过期时间 s为单位
 * @returns ref对象
 */

export function useLocalStorageRef(storeKey: string, defaultValue: any, ttlSeconds?: number) {
  const key = STORE_KEY + storeKey

  // 检查数据是否过期
  const checkExpired = (storedData) => {
    if (!storedData || !storedData._timestamp) return true

    const now = Date.now()
    const storedTime = storedData._timestamp
    const ttl = storedData._ttl * 1000 // 转换为毫秒

    return (now - storedTime) > ttl
  }

  // 获取存储的值
  const getStoredValue = () => {
    try {
      const stored = localStorage.getItem(key)
      if (!stored) return null

      const storedData = deserialize(stored)

      // 检查是否有过期时间且数据是否过期
      if (storedData._ttl && checkExpired(storedData)) {
        localStorage.removeItem(key)
        return null
      }

      return storedData
    } catch (error) {
      console.error('读取 localStorage 失败:', error)
      return null
    }
  }

  const storedData = getStoredValue()
  const data = ref(storedData ? storedData._value : defaultValue)

  onMounted(() => {
    const localStorageUpdate = () => {
      const dataToStore = {
        _value: data.value,
        _timestamp: Date.now(),
        _ttl: ttlSeconds
      }
      localStorage.setItem(key, serialize(dataToStore))
    }

    watchEffect(localStorageUpdate)
  })

  // 手动清除过期数据的方法
  //@ts-ignore
  const clearExpired = () => {
    const stored = localStorage.getItem(key)
    if (stored) {
      const storedData = deserialize(stored)
      if (storedData._ttl && checkExpired(storedData)) {
        localStorage.removeItem(key)
        data.value = defaultValue
      }
    }
  }

  // 手动设置过期时间
  //@ts-ignore
  const setWithTTL = (value: any, ttl: number) => {
    const dataToStore = {
      _value: value,
      _timestamp: Date.now(),
      _ttl: ttl
    }
    localStorage.setItem(key, serialize(dataToStore))
    data.value = value
  }

  // 反序列化数据
  function deserialize(value) {
    try {
      const deserialized = JSON.parse(value)
      if (typeof deserialized === "object" && deserialized !== null) {
        return deserialized
      } else if (typeof deserialized === "function") {
        return new Function(`return ${deserialized}`)()
      } else {
        return deserialized
      }
    } catch (e) {
      return value
    }
  }

  // 序列化数据
  function serialize(value) {
    if (typeof value === "function") {
      return value.toString()
    } else if (Array.isArray(value)) {
      return JSON.stringify(value)
    } else if (typeof value === "object" && value !== null) {
      return JSON.stringify(value)
    } else {
      return value
    }
  }

  return data
}

export default useLocalStorageRef